package action;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import common.StrutsStaticParams;

public class ActionManager 
{
	public String ManagerDriven(String actionClassPath, HttpServletRequest request)
	{
		try 
		{
			Class clz = Class.forName(actionClassPath);
			Object object = clz.newInstance();
			this.implantParams(request, object);
			Method method = clz.getDeclaredMethod("execute", null);
			String result = (String) method.invoke(object, null);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
		
		return "";
	}
	
	private void implantParams(HttpServletRequest request, Object ob) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, NoSuchFieldException
	{
		Class intf[] = ob.getClass().getInterfaces();
		Class intfe = null;
		for(int i = 0; i < intf.length; i++)
			if(intf[i].getName().equals(StrutsStaticParams.MODELDRIVEN))
			{
				intfe = intf[i];
				break;
			}
		
		if(intfe != null)
		{
			Method me[] = ob.getClass().getDeclaredMethods();

			Method method = ob.getClass().getDeclaredMethod("getModel", null);
			Object object = method.invoke(ob, null);
			if(object != null)
				ob = object;
		}
		
		Enumeration e = request.getParameterNames();
		while(e.hasMoreElements())
		{
			String paramName = (String) e.nextElement();
			System.out.println(paramName);
			Field f[] = ob.getClass().getDeclaredFields();
			Field field = ob.getClass().getDeclaredField(paramName);
			if(field != null)
			{
				Method method = ob.getClass().getDeclaredMethod("set" + (paramName.charAt(0) + "").toUpperCase() + paramName.substring(1),String.class);
				if(method != null)
					method.invoke(ob, request.getParameterValues(paramName));
			}
		}
	}
}
